import React, { PureComponent } from "react";
import {
  Text,
  View,
  Image,
  TextInput,
  Alert,
  ScrollView,
  FlatList,
  Platform,
  TouchableOpacity,
  Keyboard,
  StyleSheet,
  RefreshControl
} from "react-native";
import {
  statusBarHeight,
  safeAreaBottomHeight,
  LoginToken,
  screenHeight
} from "../../util/AdapterUtil";
import actions from "../../models/actions";
import { connect } from "react-redux";
import NavigationBar from "../../components/navigationBar";
import image from "../../assets/image";
import FlatListEmpty from "../../components/FlatListEmpty";
import FlatListFooter from "../../components/FlatListFooter";
import {
  ClassicsHeader,
  SmartRefreshControl
} from "react-native-smartrefreshlayout";
import ImageView from "../../components/ImageView";
import * as requestApi from "../../util/requestApi";
import { StackActions } from "react-navigation";

/*配送人选择列表*/
class DeliverySearchScreen extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      isRefreshing: false,
      searchText: "",
      data: [],
      loading: false,
      hasMore: true
    };
  }

  componentWillUnmount() {}

  componentDidMount() {
    this.getData();
  }

  render() {
    const { searchText, data, hasMore } = this.state;
    return (
      <View style={{ flex: 1, backgroundColor: "#F9F9F9" }}>
        <NavigationBar
          navigation={this.props.navigation}
          isBack={true}
          title={"选择配送人"}
        />

        {/*搜索框*/}
        <View
          style={{
            backgroundColor: "#F9F9F9",
            paddingLeft: 10,
            paddingRight: 10,
            paddingTop: 10,
            paddingBottom: 10,
            flexDirection: "row",
            alignItems: "center",
            width: "100%",
            height: 60,
            zIndex: 1000
          }}
        >
          <TextInput
            style={{
              flex: 1,
              height: 40,
              paddingLeft: 50,
              paddingRight: 20,
              paddingVertical: 0,
              borderTopLeftRadius: 10,
              borderBottomLeftRadius: 10,
              backgroundColor: "#E6E6E6"
            }}
            ref={e => {
              this.searchTextInput = e;
            }}
            value={searchText}
            autoFocus={false}
            placeholder={"请输入搜索内容"}
            placeholderTextColor={"#989898"}
            selectionColor={"#4A90E2"}
            autoCapitalize={"none"}
            underlineColorAndroid="transparent"
            onChangeText={text => {
              this.setState({
                searchText: text
              });
            }}
            returnKeyType={"search"}
            onSubmitEditing={() => {
              this.onSubmitText();
            }}
          />

          <TouchableOpacity
            style={{
              flexDirection: "row",
              justifyContent: "center",
              alignItems: "center",
              backgroundColor: "#4A90E2",
              borderTopRightRadius: 10,
              borderBottomRightRadius: 10,
              width: 60,
              height: "100%"
            }}
            onPress={() => {
              this.onSubmitText();
            }}
          >
            <Text style={{ color: "#fff", fontSize: 18 }}>搜索</Text>
          </TouchableOpacity>

          <Image
            style={{
              position: "absolute",
              left: 32,
              width: 20,
              height: 20
            }}
            source={image.icon_search}
          />
          {searchText.trim().length === 0 ? null : (
            <TouchableOpacity
              style={{ position: "absolute", right: 80, width: 15, height: 15 }}
              onPress={() => {
                this.clearTextInput();
              }}
            >
              <Image
                style={{
                  width: 20,
                  height: 20
                }}
                source={image.clear}
              />
            </TouchableOpacity>
          )}
        </View>

        <ScrollView
          style={{ flex: 1 }}
          alwaysBounceVertical={true}
          refreshControl={
            Platform.OS == "ios" ? (
              <RefreshControl
                refreshing={this.state.isRefreshing}
                onRefresh={() => {
                  this._onRefresh();
                }}
                backgroundColor={"#F9F9F9"}
              />
            ) : (
              <SmartRefreshControl
                ref={ref => (this.rc = ref)}
                renderHeader={<ClassicsHeader primaryColor="#F9F9F9" />}
                onRefresh={() => {
                  this._onRefresh();
                }}
              />
            )
          }
        >
          <FlatList
            style={{ backgroundColor: "#fff" }}
            scrollEnabled={false}
            data={this.state.data}
            horizontal={false}
            keyExtractor={(item, index) => index.toString()}
            renderItem={this._renderItem}
            ListEmptyComponent={() => <FlatListEmpty />}
            ListFooterComponent={() => (
              <FlatListFooter
                isShowBottom={true}
                show={data && data.length > 10 ? true : false}
                hasMore={hasMore}
              />
            )}
            onEndReached={() => {
              if (data.length >= 10) {
                //大于等于10 说明到了底部
                this.getData(searchText, false);
              }
            }}
            onEndReachedThreshold={1}
          />
        </ScrollView>
        <View style={{ height: safeAreaBottomHeight }} />
      </View>
    );
  }

  //下拉刷新
  _onRefresh = () => {
    this.setState({ isRefreshing: true });
    this.getData(this.state.searchText);

    // setTimeout(() => {
    // }, 1000);
  };

  // 提交搜索  data是搜索历史逻辑 当前未用到
  onSubmitText = data => {
    Loading.show();
    Keyboard.dismiss();
    this.setState({
      data: []
    });

    const { searchText } = this.state;
    let keyword;
    if (data) {
      keyword = data;
      this.setState({
        searchText: data
      });
    } else {
      if (searchText.trim().length === 0) {
        Toast.show("请输入搜索内容");
        Loading.hide();
        this.setState({
          searchText: "",
          loading: false
        });
        return;
      }
      keyword = searchText;
    }

    //发起搜索请求
    this.getData(keyword);
  };

  getData = (keyword = this.state.searchText, isFirstPage = true) => {
    const { data, loading, hasMore } = this.state;
    if (isFirstPage || data.length === 0 || data.length < 10) {
      // 第一页
      requestApi
        .getDeliveryList({ name: keyword, page: 1 })
        .then(res => {
          this._finishRefresh();
          this.setState({
            data: res,
            hasMore: true
          });
        })
        .catch(() => {
          this._finishRefresh();
        });
    } else {
      if (data.length === 0 || data.length < 10 || loading || !hasMore) return;

      this.setState({
        loading: true
      });
      let page = data.length / 10 + 1;
      requestApi
        .getDeliveryList({ name: keyword, page: page })
        .then(res => {
          this._finishRefresh();
          let _data = [...data, ...res];
          let _hasMore = res.total === _data.length ? false : true;
          this.setState({
            data: _data,
            hasMore: _hasMore
          });
        })
        .catch(e => {
          this._finishRefresh();
        });
    }
  };

  _finishRefresh = () => {
    Loading.hide();
    this.setState({
      loading: false
    });
    Platform.OS == "ios"
      ? this.setState({ isRefreshing: false })
      : this.rc && this.rc.finishRefresh();
  };

  // 清空输入框内容
  clearTextInput = () => {
    this.searchTextInput && this.searchTextInput.clear();
    this.setState({
      searchText: "",
      data: null
    });
    this.searchTextInput && this.searchTextInput.focus();
  };

  _renderItem = ({ item }) => (
    <MyListItem onPressItem={this._onPressItem.bind(this)} item={item} />
  );

  _onPressItem = item => {
    //回退
    this.props.navigation.dispatch(
      StackActions.pop({
        n: 1
      })
    );

    if (this.props.navigation.state.params.callback) {
      this.props.navigation.state.params.callback({
        name: item.name,
        deliveryPhone: item.phone,
        deliveryId: item.deliveryId
      });
    }
  };
}

class MyListItem extends PureComponent {
  _onPress = () => {
    this.props.onPressItem(this.props.item);
  };

  render() {
    return (
      <View style={{ height: 70, width: "100%" }}>
        <TouchableOpacity
          style={{
            backgroundColor: "#fff",
            flexDirection: "row",
            height: 60,
            paddingLeft: 15,
            paddingRight: 15,
            alignItems: "center",
            justifyContent: "center"
          }}
          onPress={this._onPress.bind(this)}
        >
          <Text style={{ color: "#606060", fontSize: 16 }}>配送人</Text>
          <View style={{ flex: 1 }} />
          <Text style={{ color: "#AAAAAA", fontSize: 14 }}>
            {this.props.item.name} {this.props.item.phone}
          </Text>
        </TouchableOpacity>

        <View
          style={{
            marginLeft: 15,
            height: 1,
            backgroundColor: "#DDDDDD",
            transform: [{ scaleY: 0.5 }]
          }}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({});

export default connect(
  ({ userInfo }) => ({
    userInfo
  }),
  {}
)(DeliverySearchScreen);
